<?php
/**
 * File: classTagCloud.php
 * 
 * This file will contain the mock ajax request from the links of 
 * the tag cloud. 
 */
/**
 * 
 */ 
include 'lib/config.php';
require_once 'lib/mockajaxfbconfig.php';
include 'iHackyFunctions.php';

   
//following if statment to recieve FORM data from the mock ajax calls
//to render a display with members
if(isset($_REQUEST['expertiseInfoSection'])){

	$conn = getDbConn(); //get db connection
	$pageNum = 1;
	$rowsPerPage = 2;
	
	//test if page number has changed from previous calls
	if(isset($_REQUEST['memberPages'])){
		$pageNum = $_REQUEST['memberPages'];
	}

	$offset = ($pageNum - 1) * $rowsPerPage;

	$keyword = $_REQUEST['expertiseInfoSection'];
	
	//mysql built in function to prevent sql injections
	$keyword = mysql_real_escape_string($keyword);

	$rank = $_REQUEST['rank'];

	//query to retrieve the number of rows of the search
	$qryGetSearchResultsCount = "SELECT CLASS.class_detail,
	CLASS_USERS.facebook_id, CLASS_USERS.time_start,
	CLASS_USERS.time_last, CLASS_USERS.time_used,
	CLASS_USERS.class_rank FROM CLASS, CLASS_USERS
	WHERE CLASS.class_id = CLASS_USERS.class_id
	AND CLASS_USERS.facebook_id != $user
	AND CLASS_USERS.class_rank != 0
	AND MATCH (class_name,class_detail) AGAINST ('\"$keyword\"' IN BOOLEAN MODE)
	ORDER BY FIELD(CLASS_USERS.class_rank, '$rank') DESC;";

	$rowCount = mysql_query($qryGetSearchResultsCount, $conn) or DIE(mysql_error()."test 1");
	$numRows = mysql_num_rows($rowCount);
	$maxPage = ceil($numRows/$rowsPerPage);

    //query to display actual data to the page
	$qryGetSearchResults = "SELECT CLASS.class_detail,
	CLASS_USERS.facebook_id, CLASS_USERS.time_start,
	CLASS_USERS.time_last, CLASS_USERS.time_used,
	CLASS_USERS.class_rank FROM CLASS, CLASS_USERS
	WHERE CLASS.class_id = CLASS_USERS.class_id
	AND CLASS_USERS.facebook_id != $user
	AND CLASS_USERS.class_rank != 0
	AND MATCH (class_name,class_detail) AGAINST ('\"$keyword\"' IN BOOLEAN MODE)
	ORDER BY FIELD(CLASS_USERS.class_rank, '$rank') DESC
	LIMIT $offset, $rowsPerPage;";

	$results = mysql_query($qryGetSearchResults, $conn) or DIE(mysql_error()."test2");

	//test to see if page is the last page, to determine the last elements number
	if($pageNum == $maxPage){
		$lastItem = $offset + ($numRows - (($pageNum - 1) * $rowsPerPage));
	}
	else{
		$lastItem = ($offset + $rowsPerPage);
	}
	$offset++;

	$counter = 1;

	if(mysql_num_rows($results) > 0){
		

        //fbml tag to render a facebook style header
		echo "<fb:header icon=\"false\" decoration=\"add_border\">
                   Search returned ".mysql_num_rows($results)." member(s)... 
               </fb:header>";
		echo '<br>';

		//prints the banner that displays the number index of the items
		echo "<div class=\"header\">";
		echo  "<div align=\"left\">
		<b><font color=\"#3B5998\">
		Displaying results: $offset - $lastItem<br>
		</font></b>
		</div>";
		echo "</div>";
		echo "<div align=\"center\">
		<b><font color=\"#666666\">
		Page $pageNum of $maxPage
		</font></b><br>
		</div>";

        echo "<table border=\"0\" width=\"100%\">
                 <tr>
                   <th bgcolor=\"#EEEEEE\">
                     Member Name 
                   </th>
                   <th bgcolor=\"#EEEEEE\">
                     Class Name 
                   </th>
                   <th bgcolor=\"#EEEEEE\">
                     Date Last Used 
                   </th>
                   <th bgcolor=\"#EEEEEE\">
                     Proficiency 
                   </th>
                  <tr>";

		//create a variable to toggle the background color for each row
		$colorFlag = false;
		
		//while loop to display information on the page
		while($resultsArray = mysql_fetch_array($results)){

			if($colorFlag){
				$color = "#FFEEFF";
			}
			else{
				$color = "#FFFFFF";
			}
			$currentID = $resultsArray['facebook_id'];

			echo "<tr bgcolor=\"$color\">";
			echo   "<td>";
			echo    "<fb:name firstnameonly=\"true\" uid=\"$currentID\"/><br>";
			echo "<a onclick=\"showdiv('$counter');\">Ask this expert for help!</a>
			<div id=\"$counter\" style=\"display: none\">";

			$counter++;
			$sender = $user;
			$recipient = $resultsArray['facebook_id'];
			$messageSubject = "Please help.";
			$messageBody = "Hi";
			$messageHandler = "store_message.php";
			$createMessage = new Message($sender, $recipient, $messageSubject, $messageBody, "Time",
                                         "0", $messageHandler);
			$result = $createMessage->createMessageForm();

			echo "<a onclick=\"showdiv('$counter');\">View User's Profile</a>
			<div id=\"$counter\" style=\"display: none\">";
			showClasses($resultsArray['facebook_id'], false);
			echo "</div>
                 </div>";

			echo   "</td>";
			echo   "<td>";
			echo     $resultsArray['class_detail'];
			echo   "</td>";
			echo   "<td>";
			echo      $resultsArray['time_last'];
			echo    "</td>";
			echo    "<td>";
			echo      $resultsArray['class_rank'];
			echo    "</td>";
			echo "</tr>";

			$colorFlag = !$colorFlag; //toggle the variable
			$counter++;
		}
		echo "</table>";
		
		//check if page is the first page, print only next link
		if($pageNum == 1 && ($numRows > $rowsPerPage)){
			$newPageNum = $pageNum + 1;
			echo '<br><br>';

			echo "<div align=\"center\">
			<form id=\"first_page\">
			<input name=\"expertiseInfoSection\" type=\"hidden\" value=\"$keyword\">
			<input name=\"memberPages\" type=\"hidden\" value=\"$newPageNum\">
			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/classTagCloud.php\"
			clickrewriteform=\"first_page\"
			clickrewriteid=\"CommunityExpertise\">
			Next
			<img src=\"http://www.ikoaguild.com/ihacky/images/forwardarrow.png\" align=\"top\">
			</a>
			</form>
			</div>";

		}
		//check to see if page is between first and last, then print previous and next links
		else if($pageNum < $maxPage){
			echo '<br><br>';
			$previousPageNum = $pageNum - 1;
			echo "<div align=\"center\">
			<table>
			<tr>
			<td>

			<form id=\"pre_page\">
			<input name=\"expertiseInfoSection\" type=\"hidden\" value=\"$keyword\">
			<input name=\"memberPages\" type=\"hidden\" value=\"$previousPageNum\">

			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/classTagCloud.php\"
			clickrewriteform=\"pre_page\"
			clickrewriteid=\"CommunityExpertise\">
			<img src=\"http://www.ikoaguild.com/ihacky/images/reversearrow.png\" align=\"top\">
			Previous
			</a>
			</form>

			</td>";
			$nextPageNum = $pageNum + 1;
			echo "<td>

			<form id=\"next_page\">
			<input name=\"expertiseInfoSection\" type=\"hidden\" value=\"$keyword\">
			<input name=\"memberPages\" type=\"hidden\" value=\"$nextPageNum\">
			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/classTagCloud.php\"
                clickrewriteform=\"next_page\"
                clickrewriteid=\"CommunityExpertise\">
                Next
                <img src=\"http://www.ikoaguild.com/ihacky/images/forwardarrow.png\" align=\"top\">
			</a>
			</form>

			</td>
			</tr>
			</table>
			</div>";
		}
		//check to see if page is last page, then print only previous link
		else if($pageNum == $maxPage && ($numRows > $rowsPerPage)){
			echo '<br><br>';
			$newPageNum = $pageNum - 1;
			echo "<div align=\"center\">
			<form id=\"last_page\">
			<input name=\"expertiseInfoSection\" type=\"hidden\" value=\"$keyword\">
			<input name=\"memberPages\" type=\"hidden\" value=\"$newPageNum\">

			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/classTagCloud.php\"
			clickrewriteform=\"last_page\"
			clickrewriteid=\"CommunityExpertise\">
			<img src=\"http://www.ikoaguild.com/ihacky/images/reversearrow.png\" align=\"top\">
			Previous
			</a>
			</form>
			</div>";
		}
	}
	else{   

		echo "<fb:header icon=\"false\" decoration=\"add_border\">
           Search returned 0 member(s)...</fb:header><br>";

	}
	closeDb($conn);  //close db connection
	exit;
}

//following if statement to recieve mock ajax to render a tag cloud detail section
//containing the actual class names instead of package names, which each link will 
//retrieve members associated with the selected tag
if(isset($_POST['tagsDetailInput'])){
	
	$packagePath = $_POST['tagsDetailInput'];
	
	$conn = getDbConn(); //get datbase connection

	//create a counter for creating form id, so each rendered form will have 
	//unique ids
	$counter = 1;
	
	//query to retrieve class names from database
	$queryClassUsersCount = "SELECT cls.class_detail AS \"tag detail\", cls.class_name as tag,
	    COUNT( cu.facebook_id ) AS count
	    FROM CLASS_USERS cu 
	    JOIN CLASS cls ON ( cu.class_id = cls.class_id )
	    WHERE cu.class_rank != 0 AND MATCH (class_name, class_detail)
	    AGAINST ('\"$packagePath\"' IN BOOLEAN MODE)
	    GROUP BY cls.class_name
	    ORDER BY cls.class_name ASC";
	
	$result = mysql_query($queryClassUsersCount, $conn) or DIE(mysql_error()."Error: queryClassUsersCount");
	
	// Iterate through results and store in an array in order to calculate the font size of each tag
	while ($row = mysql_fetch_array($result)) {
	
	    // Break up package path with period as delimiter
	    $tagDetailArray = explode(".", $row['tag detail']);
	    // Remove the class name from the package path
	    $poppedIndex = array_pop($tagDetailArray);
	    // Reconstruct package path without class name
	    $tagDetailString = implode(".", $tagDetailArray);
	
	    // Do not include classes with non alphabetic characters.
	    if (preg_match("/[^A-Za-z]/", $poppedIndex) == 0) {
	        $tags[$row['tag']] = $row['count'];
	
	        // Count the number of classes in the package
	        if (!array_key_exists($tagDetailString, $tagsDetail)) {
	            $tagsDetail[$tagDetailString] = 1;
	        }
	        else {
	            $tagsDetail[$tagDetailString]++;
	        }
	    }
	}
	//print_r($tagsDetail);
	
	// Close database connection.
	closeDb($conn);
	
	//preg_match("/.[A-Za-z0-9]/", $row['tag']);
	// Font size range
	$maxSize = 32; // Max font size in px
	$minSize = 10; // Min font size in px
	
	// Get the largest and smallest array values
	$maxCount = max(array_values($tags));
	$minCount = min(array_values($tags));
	
	// Find the range of values
	$range = $maxCount - $minCount;
	// Prevent division by zero.
	if (0 == $range) {
	    $range = 1;
	}
	
	// Determine the font-size increment
	// This is the increase per tag quantity (times used)
	$increment = ($maxSize - $minSize) / ($range);
	
	$cloud_html = '';
	$cloud_tags = array();
	
	// Iterate through tag array
	foreach ($tags as $key => $value) {

	    // Calculate the font size
	    //$size = $minSize + ($value - $minCount) * ($maxSize - $minSize) / $spread;
	    $size = $minSize + (($value - $minCount) * $increment);
	
	    $cloud_tags[] = '
	    <form id="'.$counter.'">
			<input name="expertiseInfoSection" type="hidden" value="'.$key.'">
			<input name="rank" type="hidden" value="1">
			       
	    <a  clickrewriteurl="http://www.ikoaguild.com/ihacky/classTagCloud.php"
			clickrewriteform="'.$counter.'"
			clickrewriteid="CommunityExpertise"
	        style="font-size: '. floor($size) . 'px' . '" class="tag_cloud" 
	        title="There are ' . $value . ' known classes in the \'' . $key . '\' package">'
	        . htmlspecialchars(stripslashes($key)) .
	    '</a>
	    </form>';
	}
	
	$cloud_html = join("\n", $cloud_tags) . "\n";
	
	//echo '<div id="expertise_content">';
	print $cloud_html;
	//echo '</div>';
}	
?>